package create

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/urfave/cli/v2"
	"gluenet/internal/client/util"
	"io"
	"io/ioutil"
	"mime/multipart"
	"os"
	"path"
	"sigs.k8s.io/kustomize/kyaml/yaml"
)

const (
	cliUrl          = "http://39.101.140.145:30000"
	PlatformGluenet = "gluenets"
	PLATFORM_K8S    = "kubernetes"
)

type RequestConfig struct {
	Name         string      `json:"name" yaml:"name"`
	Describe     string      `json:"describe" yaml:"describe"`
	Kind         string      `json:"kind" yaml:"kind"`
	Version      string      `json:"version" yaml:"version"`
	Platform     string      `json:"platform" yaml:"platform"`
	Label        string      `json:"label" yaml:"label"`
	DetailValues interface{} `json:"detail_values" yaml:"detail_values"`
}

func config(ctx *cli.Context) error {
	var reqBody []byte

	if ctx.IsSet("file") {
		filePath := ctx.String("file")
		f, err := ioutil.ReadFile(filePath)
		if err != nil {
			return err
		}

		var requestConfig RequestConfig
		fileType := path.Ext(filePath)
		switch fileType {
		case ".json":
			err = yaml.Unmarshal(f, &requestConfig)
			if err != nil {
				return err
			}
			reqBody = f
		case ".yaml":
			err = yaml.Unmarshal(f, &requestConfig)
			if err != nil {
				return err
			}
			reqBody, err = json.Marshal(requestConfig)
			if err != nil {
				return err
			}
		default:
			return errors.New("Unexpected config file type: " + fileType)
		}
		if requestConfig.Platform != PlatformGluenet {
			return errors.New(fmt.Sprintf("Config file must belong to *gluenet* platform, got %s instead",
				requestConfig.Platform))
		}

		resp, err := util.HttpRequest("POST", cliUrl+"/apis/config/create", reqBody)
		if err != nil {
			return err
		}
		fmt.Println(string(resp))

	} else if ctx.IsSet("helm-charts") {
		filename := ctx.String("helm-charts")

		bodyBuf := new(bytes.Buffer)
		bodyWriter := multipart.NewWriter(bodyBuf)
		fileWriter, err := bodyWriter.CreateFormFile("file", filename)
		if err != nil {
			return err
		}

		f, err := os.Open(filename)
		if err != nil {
			return err
		}
		defer f.Close()

		_, err = io.Copy(fileWriter, f)
		if err != nil {
			return err
		}

		contentType := bodyWriter.FormDataContentType()
		fmt.Println(contentType)
		bodyWriter.Close()

		resp, err := util.HttpRequest("POST", cliUrl+"/apis/config/create", bodyBuf.Bytes(), contentType)
		if err != nil {
			return err
		}
		fmt.Println(string(resp))
	} else {
		return errors.New("create config needs at least 1 flag, see \"-h\" for help")
	}

	fmt.Println("Succeed")

	return nil
}
